package com.wanlian.router.ui.me;

import android.Manifest;
import android.app.Activity;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.smart.android.image.ImageLoader;
import com.smart.android.ui.BaseActivity;
import com.smart.android.ui.app.IntentResult;
import com.smart.android.utils.DateTime;
import com.smart.android.utils.Logger;
import com.wanlian.router.GlobalInfo;
import com.wanlian.router.R;
import com.wanlian.router.bean.User;
import com.wanlian.router.net.NetWorkingClient;
import com.wanlian.router.net.ResponseData;
import com.wanlian.router.net.internal.INetCallBack;
import com.wanlian.router.ui.main.yun.PicturePreviewActivity;

import java.io.File;
import java.util.Date;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * Created by Hyu on 2018/9/19.
 * Email: fvaryu@163.com
 */

@RuntimePermissions
public class UserProfileActivity extends BaseActivity {

    @BindView(R.id.image_avatar)
    ImageView mAvatar;
    @BindView(R.id.tv_nickname)
    TextView mNickname;
    @BindView(R.id.tv_gender)
    TextView mGender;

    @BindView(R.id.tv_birthday)
    TextView mBirthday;
    @BindView(R.id.tv_email)
    TextView mEmail;

    @BindView(R.id.tv_account)
    TextView mAccount;



    String Gallery_num = "";
    String CameraPhoto_Num = "";
    File mFile1, mFile2;

    @Override
    protected int layout() {
        return R.layout.activity_user_profile;
    }

    @Override
    public void initUI() {
        super.initUI();
        setTitle("个人资料");
    }

    @Override
    public void initData() {
        super.initData();

    }

    @Override
    protected void onResume() {
        super.onResume();

        update();
    }

    private void update() {
        User user = GlobalInfo.getInstance().getUser();
        mNickname.setText(user.getUsername());


        ImageLoader.loadCircle(this, user.getHeadImg(), mAvatar);
        mAccount.setText(GlobalInfo.getInstance().getAppData().getAccount());
        mBirthday.setText(DateTime.getDateByb(user.getBirthday()));
        mGender.setText(user.isSex() ? "男" : "女");
        mEmail.setText(user.getEmail());
    }

    @OnClick(R.id.image_avatar)
    void check() {
        String avatar = GlobalInfo.getInstance().getUser().getHeadImg();
        if (TextUtils.isEmpty(avatar)) {
            return;
        }
        AvatarPicturePreviewActivity.go(getActivity(), avatar);
    }

    @OnClick(R.id.rl_avatar)
    void avatar() {
        UserProfileActivityPermissionsDispatcher.openCameraWithPermissionCheck(this);
    }

    @OnClick(R.id.ll_nickname)
    void nickname() {
        redirectActivity(NickNameModifyActivity.class);
    }

    @OnClick(R.id.ll_gender)
    void gender() {

        new AlertDialog.Builder(getActivity())
                .setSingleChoiceItems(new String[]{"男", "女"}, GlobalInfo.getInstance().getUser().isSex() ? 0 : 1, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        GlobalInfo.getInstance().getUser().setSex(which == 0);
                        modify();
                    }
                })
                .create().show();
    }

    @OnClick(R.id.ll_birthday)
    void birthday() {

        new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
               GlobalInfo.getInstance().getUser().setBirthday(date.getTime());
               modify();
            }
        }).setCancelColor(getColorById(R.color.color_66))
                .build().show();
    }

    @OnClick(R.id.ll_email)
    void email() {
        redirectActivity(EmailModifyActivity.class);
    }




    /**
     * 更新UI
     *
     * @param f
     */
    private void UpdateUI(File f) {
        if (f != null) {
            if (isImageFile(f.getName())) {
                mFile2 = f;
                String pathImage = mFile2.getPath();

                NetWorkingClient.getInstance().uploadFile(getActivity(), new File(pathImage), new INetCallBack() {
                    @Override
                    public void onFinish(ResponseData response, @Nullable Object o) {
                        if (response.isSuccess()) {
                            ImageLoader.loadCircle(getActivity(), response.getUrl(), mAvatar);
                            GlobalInfo.getInstance().getUser().setHeadImg(response.getUrl());
                            modify();
                        }
                    }
                });
                Logger.i("本地剪裁后的图片名称=" + pathImage);
//                takenDoneWithStr(pathImage);
            }
        }
    }

    private void modify() {
        NetWorkingClient.getInstance().modifyUser(getActivity(), GlobalInfo.getInstance().getUser(), new INetCallBack<User>() {
            @Override
            public void onFinish(ResponseData response, @Nullable User user) {
                if (response.isSuccess()) {

                    showToast("修改成功");
                    if (user == null) {
                        return;
                    }
                    GlobalInfo.getInstance().setUser(user);
                    update();
                }else {
                    showToast(response.getMessage());
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case IntentResult.RS_CAMERA:

                    File f = new File(getExternalCacheDir(), "Camera_" + CameraPhoto_Num + ".jpg");
                    if (f.length() > 0) {

                        mFile1 = f;
                        mFile2 = new File(getExternalCacheDir(), "c" + mFile1.getName());
//                        CropImageUri(Uri.fromFile(mFile1), Uri.fromFile(mFile2), BaseIntentResult.RS_CROP);

                        Uri uri, outUri;
                        if (Build.VERSION.SDK_INT >= 24) {
                            uri = getImageContentUri(this, mFile1);
                        } else {
                            uri = Uri.fromFile(mFile1);
                        }
                        outUri = Uri.fromFile(mFile2);
                        CropImageUri(uri, outUri, IntentResult.RS_CROP);
                    }
                    break;
                case IntentResult.RS_GALLERY:
                    if (data != null) {
                        Gallery_num = System.currentTimeMillis() + "";//照片name
                        File f1 = new File(getExternalCacheDir(), "phote_" + Gallery_num + ".jpg");
                        CropImageUri(data.getData(), Uri.fromFile(f1), IntentResult.RS_CROP_GALLERY);
                    }

                    break;
                case IntentResult.RS_CROP:

                    try {
                        mFile2 = new File(getExternalCacheDir(), "c" + mFile1.getName());
                        if (mFile2.exists()) {
                            if (mFile2.length() > 0) {

                                UpdateUI(mFile2);

                            }
                        } else {
//								Toast.makeText(MyInformationActivity.this, R.string.pic_load_fail, 300).show();
                        }
                    } catch (Exception e) {
                    }


                    break;
                case IntentResult.RS_CROP_GALLERY:
                    try {
                        File mFile2 = new File(getExternalCacheDir(), "phote_" + Gallery_num + ".jpg");//"p_" +
                        if (mFile2.exists()) {
                            if (mFile2.length() > 0) {
                                UpdateUI(mFile2);
                            }
                        } else {
//								Toast.makeText(MyInformationActivity.this, R.string.pic_load_fail, 300).show();
                        }
                    } catch (Exception e) {
                    }

                    break;
            }
        } else if (resultCode == Activity.RESULT_CANCELED) {

        }
    }

    void askCamera() {
        new AlertDialog.Builder(this)
                .setTitle(R.string.ask_permission)
                .setMessage(R.string.tip_camera_permission)
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                }).setPositiveButton(R.string.to_setting, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS);
                startActivity(intent);
                finish();
            }
        }).setCancelable(false).create().show();
    }


    private void select() {


        // 从相册中选择
        Intent intent1 = new Intent(Intent.ACTION_PICK, null);
        // 添加数据
        intent1.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        // 数据类型
        intent1.setType("image/*");
        startActivityForResult(intent1, IntentResult.RS_GALLERY);

    }

    public void take() {
        try {
            if (getActivity() != null) {
                File dir = getActivity().getExternalCacheDir();
                if (dir != null) {
                    CameraPhoto_Num = System.currentTimeMillis() + "";
                    Intent intentCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File f = new File(dir, "Camera_" + CameraPhoto_Num + ".jpg");

                    Uri uri;
                    if (Build.VERSION.SDK_INT >= 24) {
                        uri = FileProvider.getUriForFile(getApplicationContext(), getApplicationContext().getPackageName() + ".fileprovider", f);
                    } else {
                        uri = Uri.fromFile(f);
                    }
                    intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                    startActivityForResult(intentCamera, IntentResult.RS_CAMERA);
                }
            }
        } catch (Exception e) {
        }

    }

    @NeedsPermission(Manifest.permission.CAMERA)
    void openCamera() {

        new AlertDialog.Builder(getActivity())
                .setItems(new String[]{"拍照", "相册"}, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0: {
                                take();
                            }
                            break;
                            case 1: {
                                select();
                            }
                            break;
                        }
                    }
                }).create().show();

//        selectFun("manageruserlogo.jpg");
    }

    @OnShowRationale(Manifest.permission.CAMERA)
    void showRationaleForCamera(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setTitle(R.string.ask_permission)
                .setMessage(R.string.tip_camera_permission)
                .setNegativeButton(R.string.button_deny, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        request.cancel();
                    }
                }).setPositiveButton(R.string.button_allow, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                request.proceed();
            }
        }).setCancelable(false).create().show();
    }


    @OnPermissionDenied(Manifest.permission.CAMERA)
    void onDeniedForLocation() {
        askCamera();
    }

    @OnNeverAskAgain(Manifest.permission.CAMERA)
    void onNeverAskAgain() {
        askCamera();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        UserProfileActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }


    /**
     * 2 图像剪裁
     *
     * @param uri         原始图片uri
     * @param outuri      输出的图片uri
     * @param requestCode
     */
    private void CropImageUri(Uri uri, Uri outuri, int requestCode) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", getCropWith() * 2);
        intent.putExtra("aspectY", getCropHeight() * 2);
        intent.putExtra("outputX", getCropWith() * 2);
        intent.putExtra("outputY", getCropHeight() * 2);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outuri);
        intent.putExtra("return-data", false);
        intent.putExtra("scaleUpIfNeeded", true);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
//        startActivityForResult(intent, requestCode);
        ComponentName componentName = intent.resolveActivity(getPackageManager());
        if (componentName != null) {
            startActivityForResult(intent, requestCode);
        }
    }


    //获取文件的Content uri路径
    public static Uri getImageContentUri(Context context, File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media._ID},
                MediaStore.Images.Media.DATA + "=? ",
                new String[]{filePath}, null);

        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor
                    .getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }


    private static boolean isImageFile(String filename) {
        String s = filename.toLowerCase();
        return (s.endsWith(".jpeg") ||
                s.endsWith(".jpg") ||
                s.endsWith(".gif") ||
                s.endsWith(".bmp") ||
                s.endsWith(".png")
        );
    }

    public int getCropWith() {
        return 640;
    }

    public int getCropHeight() {
        return 640;
    }
}
